<?php

namespace App\Http\Controllers\Admin;

use App\User;
use DB;
use App\Http\Requests\Admin\UsersRequest;

class usersInfoController extends MasterController
{
    protected $takeRows = 100;

    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $users = DB::table('users')->take($this->takeRows)->orderBy('created_at')->get();
        $count = DB::table('users')->count('*');
        $data = array(
            'users' => $users,
            'count' => $count
        );
        return view('admin.userinfo.usersInfo', compact('data'));
    }

    public function searchByUsername($name='')
    {
        if ($name == '') {
            $users = User::where('id','<>','')->orderBy('created_at')->take($this->takeRows)->get();
            $count = User::all()->count('*');
        } else {
            $users = User::where('name', 'like', '%' . $name . '%')
                ->orderBy('created_at')
                ->take($this->takeRows)
                ->get();
            $count = User::where('name', 'like', '%' . $name . '%')
                ->orderBy('created_at')
                ->count('*');
        }
        return response()->json([
            'users' => $users,
            'count' => $count
        ]);
    }

    public function loadData($start, $searchText = '')
    {
        if ($searchText == '') {
            $users = User::all()->orderBy('created_at')->skip($start)->take($this->takeRows)->get();
        } else {
            $users = User::where('name', 'like', '%' . $searchText . '%')
                ->orderBy('created_at')
                ->skip($start)
                ->take($this->takeRows)
                ->get();
        }
        return response()->json([
            'users' => $users
        ]);
    }

    public function changeName(UsersRequest $request)
    {
        $count = User::where('name', $request['name'])
            ->where('id', '<>', $request['id'])->count('*');
        if ($count > 0) {
            return parent::error('此用户名已被占用！');
        }

        User::where('id', $request['id'])->update([
            'name' => $request['name']
        ]);
        return response()->json([
            'status_code' => 200,
            'name' => $request['name'],
        ],200);

    }
}
